/* eslint-disable no-unused-vars */
function ajaxFn({ baseUrl, url, method = 'GET', data = {}, headers = {} }) {
    return new Promise((res, rej) => {
        let xhr = new XMLHttpRequest();
        //判断是否为get请求，参数是需要拼接在url上
        let query = '?';
        if (Object.keys(data).length) {
            for (const key in data) {
                query += `${key}=${data[key]}&`;
            }
        }
        function setHeaders() {
            //设置请求头
            if (Object.keys(headers).length) {
                for (const key in headers) {
                    const element = headers[key];
                    xhr.setRequestHeader(key, element);
                }
            }
        }
        if (method.toUpperCase() === 'GET') {
            xhr.open(method, baseUrl + url + query.slice(0, -1));
            setHeaders();
            xhr.send();
        } else {
            xhr.open(method, baseUrl + url);
            setHeaders();
            //请求体要求发送一个json字符串
            xhr.send(JSON.stringify(data));
        }

        //监听请求的状态
        xhr.addEventListener('readystatechange', () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    res(JSON.parse(xhr.response));
                } else {
                    //可能出现的报错，一般后端都会有响应报错信息，也需要返回回去回调函数
                    rej(JSON.parse(xhr.response));
                }
            }
        });
    });
}
